package com.zx.notification.producer.service.impl;

import com.zx.notification.common.constants.NotificationConstants;
import com.zx.notification.common.dao.NotificationTemplatesMapper;
import com.zx.notification.common.model.NotificationTemplates;
import com.zx.notification.producer.service.INotificationTemplatesService;
import com.zx.redis.block.service.RedisBlockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * description: 通知模板服务实现类 <br>
 * create: 2025-10-23
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationTemplatesServiceImpl implements INotificationTemplatesService {

    private final NotificationTemplatesMapper notificationTemplatesMapper;
    private final RedisBlockService redisBlockService;

    /**
     * 根据模板编码获取模板
     *
     * @param templateCode 模板编码
     * @return 通知模板
     */
    @Override
    public NotificationTemplates getTemplateByCode(String templateCode) {
        String cacheKey = NotificationConstants.RedisCache.TEMPLATE_CACHE_KEY_PREFIX + templateCode;
        NotificationTemplates template = redisBlockService.getCachedObject(cacheKey, NotificationTemplates.class);
        if (template == null) {
            // 缓存中不存在，从数据库获取
            template = notificationTemplatesMapper.selectByTemplateCode(templateCode);
            if (template != null) {
                // 存入缓存，设置过期时间
                redisBlockService.setCacheObject(cacheKey,
                        template,
                        NotificationConstants.RedisCache.TEMPLATE_CACHE_EXPIRE_TIME,
                        TimeUnit.SECONDS);
            }
        }

        return template;
    }
}